package com.learn.spring;

import com.learn.spring.handler.FluxHandler;
import com.learn.spring.service.FluxService;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.netty.http.server.HttpServer;

import java.io.IOException;

import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.reactive.function.server.RequestPredicates.*;
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;

public class WebfluxService {

    public static void main(String[] args) throws IOException {
        WebfluxService service = new WebfluxService();
        service.createReactorServer();
        System.out.println("按回车退出");
        System.in.read();
    }

    // 1. 创建 Router 路由
    public RouterFunction<ServerResponse> routingFunction() {
        FluxService fluxService = new FluxService();
        FluxHandler handler = new FluxHandler(fluxService);

        return RouterFunctions
                .route(GET("/user/{id}").and(accept(APPLICATION_JSON)), handler::findUserById)
                .andRoute(GET("/user").and(accept(APPLICATION_JSON)), handler::allUser)
                .andRoute(POST("/user").and(accept(APPLICATION_JSON)), handler::addUser);
    }

    // 2. 创建服务完成适配
    public void createReactorServer() {
        // 路由和 handler 适配
        RouterFunction<ServerResponse> route = routingFunction();
        HttpHandler httpHandler = toHttpHandler(route);
        ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);

        // 创建服务器
        HttpServer httpServer = HttpServer.create();
        httpServer.handle(adapter).port(8088).bindNow();
    }

}
